<template>
  <dl-card style="max-width: 99%">
    <el-form :inline="true" :model="page" class="demo-form-inline">
      <el-form-item label="调拨编号">
        <el-input v-model="page.transfer_no" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="入场状态">
        <el-select v-model="page.inbound_status" placeholder="请选择" clearable  style="width: 100px;">
          <el-option label="待入库" :value="0" />
          <el-option label="已入库" :value="1" />

        </el-select>
      </el-form-item>
      <el-form-item label="出库">
        <el-select v-model="page.outbound_status" placeholder="请选择" clearable  style="width: 100px;">
       <el-option label="待出库" :value="0" />
          <el-option label="已出库" :value="1" />
          <el-option label="驳回" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="page.status" placeholder="请选择" clearable style="width: 100px;" >
          <el-option label="待审核" :value="1" />
           <el-option label="驳回" :value="2" />
          <el-option label="通过" :value="3" />
           <el-option label="已完成" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTransfer">查找</el-button>
      </el-form-item>
    </el-form>
  </dl-card>
  <dl-card style="max-width: 99%">
    <el-button type="success" @click="addMaterial">新增物料</el-button>
    <el-button type="danger" @click="deleteMaterial">删除</el-button>
    <el-button type="primary" @click="updateMaterial">修改</el-button>
   <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" border highlight-current-row fit
      @selection-change="handleSelectionChange">
  <el-table-column type="selection" width="55" />
  <el-table-column type="index" label="序号" align="center" />
<el-table-column prop="transfer_no" label="调拨单号" align="center">
  <template #default="{ row }">
    <el-button link type="primary" @click="showDetail(row)">{{ row.transfer_no }}</el-button>
  </template>
</el-table-column>
  <el-table-column prop="status" label="单据状态" align="center">
    <template #default="{ row }">
      <el-tag :type="getStatusTagType(row.status)">
        {{ getStatusText(row.status) }}
      </el-tag>
    </template>
  </el-table-column>
  <el-table-column prop="create_time" label="调拨申请日期" align="center">
    <template #default="{ row }">
      {{ formatDate(row.create_time) }}
    </template>
  </el-table-column>
  <el-table-column prop="transfer_type" label="调拨类型" align="center" />
  <el-table-column prop="out_warehouse_id" label="调出仓库" align="center">
    <template #default="{ row }">
      {{ getWarehouseName(row.out_warehouse_id) }}
    </template>
  </el-table-column>
  <el-table-column prop="in_warehouse_id" label="调入仓库" align="center">
    <template #default="{ row }">
      {{ getWarehouseName(row.in_warehouse_id) }}
    </template>
  </el-table-column>
  <el-table-column label="商品名称" align="center">
    <template #default="{ row }">
      <span v-if="row.detail && row.detail.length">
        {{ row.detail[0].goods_name || '无' }}
      </span>
      <span v-else>无</span>
    </template>
  </el-table-column>
  <el-table-column label="商品编码" align="center">
    <template #default="{ row }">
      <span v-if="row.detail && row.detail.length">
        {{ row.detail[0].goods_code || '无' }}
      </span>
      <span v-else>无</span>
    </template>
  </el-table-column>
  <el-table-column label="规格型号" align="center">
    <template #default="{ row }">
      <span v-if="row.detail && row.detail.length">
        {{ row.detail[0].specification || '无' }}
      </span>
      <span v-else>无</span>
    </template>
  </el-table-column>
  <el-table-column label="单位" align="center">
    <template #default="{ row }">
      <span v-if="row.detail && row.detail.length">
        {{ row.detail[0].unit || '无' }}
      </span>
      <span v-else>无</span>
    </template>
  </el-table-column>
  <el-table-column label="数量" align="center">
    <template #default="{ row }">
      <span v-if="row.detail && row.detail.length">
        {{ row.detail[0].quantity || '无' }}
      </span>
      <span v-else>无</span>
    </template>
  </el-table-column>
  <el-table-column label="单价" align="center">
    <template #default="{ row }">
      <span v-if="row.detail && row.detail.length">
        {{ row.detail[0].price || '无' }}
      </span>
      <span v-else>无</span>
    </template>
  </el-table-column>
  <el-table-column label="金额" align="center">
    <template #default="{ row }">
      <span v-if="row.detail && row.detail.length">
        {{ row.detail[0].amount || '无' }}
      </span>
      <span v-else>无</span>
    </template>
  </el-table-column>
  <el-table-column label="出库状态" align="center">
    <template #default="{ row }">
        <el-tag :type="getStatusTag(row.detail[0].outbound_status)">
          {{ getoutbound_status(row.detail[0].outbound_status)}}
        </el-tag>
    </template>
  </el-table-column>
  <el-table-column label="入库状态" align="center">
    <template #default="{ row }">
              <el-tag :type="getStatusTag(row.detail[0].inbound_status)">
          {{ getinbound_status(row.detail[0].inbound_status)}}
        </el-tag>
    </template>
  </el-table-column>
  <el-table-column label="经办人" align="center">
    <template #default="{ row }">
      {{ row.name || '无' }}
    </template>
  </el-table-column>
  <el-table-column label="制单时间" align="center">
    <template #default="{ row }">
      {{ formatDate(row.create_time) }}
    </template>
  </el-table-column>
  <el-table-column label="审核人" align="center">
    <template #default="{ row }">
      {{ row.auditor_id || '无' }}
    </template>
  </el-table-column>
  <el-table-column label="审核时间" align="center">
    <template #default="{ row }">
      {{ formatDate(row.audit_time) }}
    </template>
  </el-table-column>
  <el-table-column fixed="right" label="操作" align="center" width="180">
    <template #default="scope">
      <el-button link type="primary" size="small" @click="showDetail(scope.row)">详情</el-button>
    </template>
  </el-table-column>
</el-table>
    <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize" :total="page.totalCount"
      layout="total, sizes, prev, pager, next, jumper" @size-change="getTransfer" @current-change="getTransfer" />
  </dl-card>

  <!-- 物料添加/编辑对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="ruleForm.id ? '编辑调拨单' : '新增调拨单'" width="1250">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="130px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="调拨编号" prop="transfer_no">
            <el-input v-model="ruleForm.transfer_no" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨类型" prop="transfer_type">
            <el-select v-model="ruleForm.transfer_type" placeholder="请选择调拨类型">
              <el-option label="货品调拨" value="货品调拨" />
               <el-option label="库存调拨" value="库存调拨" />
              <el-option label="满仓调拨" value="满仓调拨" />
              <el-option label="其他调拨" value="其他调拨" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨日期" prop="create_time">
            <el-date-picker v-model="ruleForm.create_time" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="调出仓库" prop="out_warehouse_id">
            <el-select v-model="ruleForm.out_warehouse_id" placeholder="请选择调出仓库" >
              <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name"
                :value="warehouse.id" />
            </el-select>
          </el-form-item>
        </el-col><el-button  key="plain" type="primary"link @click="Ikun">设置</el-button>
        <el-col :span="8">
          <el-form-item label="调入仓库" prop="in_warehouse_id">
            <el-select v-model="ruleForm.in_warehouse_id" placeholder="请选择调入仓库" >
              <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name"
                :value="warehouse.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="经办人" prop="operator_id">
            <el-select v-model="ruleForm.operator_id" placeholder="请选择经办人">
              <el-option v-for="user in userList" :key="user.id" :label="user.name" :value="user.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注">
            <el-input v-model="ruleForm.remark" placeholder="请输入备注" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="section-header">
        <span class="section-title">配件信息</span>
        <el-button size="small" type="primary" @click="addHealthRow">新增配件</el-button>
      </div>

      <el-table :data="ruleForm.detail" border style="width: 100%; margin-top: 10px;">
        <el-table-column label="商品" width="200">
          <template #default="{ row, $index }">
          <el-select 
                        v-if="row.editing" 
                        v-model="row.goods_id" 
                        placeholder="请选择商品" 
                        filterable 
                        clearable
                        @change="(val: number | null) => handleGoodsChange(val, $index)"
>
              <el-option v-for="goods in goodsList" :key="goods.id" :label="`${goods.name} (${goods.code})`"
                :value="goods.id">
                <span style="float: left">{{ goods.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ goods.code }}</span>
              </el-option>
            </el-select>
            <template v-else>
              {{ row.goods_name }} ({{ row.goods_code }})
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格型号" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="goods_type" label="货品类型" width="100" />
        <el-table-column label="调拨数量" width="120">
          <template #default="{ row }">
            <el-input-number v-if="row.editing" v-model="row.quantity" :min="1" :precision="0" controls-position="right"
              size="small" />
            <template v-else>{{ row.quantity }}</template>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" width="100" />
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="{ row }">
            {{ calculateAmount(row) }}
          </template>
        </el-table-column>
        <el-table-column label="调出仓库的库存" width="120">
          
        <template #default="{ row }"> 
    <el-input  v-if="row.editing" v-model="row.out_stock"  :min="1" :precision="0" controls-position="right" size="small" />
     <template v-else>{{ row.out_stock }}</template>
  </template>
        </el-table-column>
 <el-button type="primary">设置</el-button>
        <el-table-column label="调入仓库的库存" width="120">
  <template #default="{ row }">
    <el-input v-if="row.editing"  v-model="row.in_stock" :min="1" :precision="0" controls-position="right" size="small" />
     <template v-else>{{ row.in_stock }}</template>
  </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row, $index }">
            <template v-if="row.editing">
              <el-button link type="primary" size="small" @click="saveRow(row)">保存</el-button>
              <el-button link type="danger" size="small" @click="cancelEdit(row, $index)">取消</el-button>
            </template>
            <template v-else>
              <el-button link type="primary" size="small" @click="editRow(row)">编辑</el-button>
              <el-button link type="danger" size="small" @click="deleteRow($index)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        共 {{ ruleForm.detail.length }} 条记录
      </div>

      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-form>
  </el-dialog>

<!-- 详情对话框 -->
<el-dialog v-model="detailDialogVisible" title="调拨单详情" width="1000">
  <el-descriptions :column="2" border>
    <el-descriptions-item label="调拨单号">{{ currentDetail.transfer_no }}</el-descriptions-item>
    <el-descriptions-item label="调拨类型">{{ currentDetail.transfer_type }}</el-descriptions-item>
    <el-descriptions-item label="调拨日期">{{ formatDate(currentDetail.create_time) }}</el-descriptions-item>
    <el-descriptions-item label="调出仓库">{{ getWarehouseName(currentDetail.out_warehouse_id) }}</el-descriptions-item>
    <el-descriptions-item label="调入仓库">{{ getWarehouseName(currentDetail.in_warehouse_id) }}</el-descriptions-item>
    <el-descriptions-item label="经办人">{{ getUserName(currentDetail.operator_id) }}</el-descriptions-item>
    <el-descriptions-item label="状态">
      <el-tag :type="getStatusTagType(currentDetail.status)">
        {{ getStatusText(currentDetail.status) }}
      </el-tag>
    </el-descriptions-item>
    <el-descriptions-item label="备注">{{ currentDetail.remark || '无' }}</el-descriptions-item>
  </el-descriptions>

  <div class="section-header" style="margin-top: 20px;">
    <span class="section-title">调拨明细</span>
  </div>

  <el-table :data="detailMaterialInformationList" border style="width: 100%; margin-top: 10px;">
    <el-table-column type="index" label="序号" width="60" align="center" />
    <el-table-column prop="goods_name" label="商品名称" width="150" />
    <el-table-column prop="goods_code" label="商品编码" width="120" />
    <el-table-column prop="specification" label="规格型号" width="120" />
    <el-table-column prop="unit" label="单位" width="80" />
    <el-table-column prop="quantity" label="数量" width="100" align="right" />
    <el-table-column prop="price" label="单价" width="100" align="right" />
    <el-table-column prop="amount" label="金额" width="100" align="right" />
    <el-table-column prop="outbound_status" label="出库状态" width="100">
      <template #default="{ row }">
         <el-tag :type="row.outbound_status">
          {{ getinbound_status(row.outbound_status)}}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="inbound_status" label="入库状态" width="100">
      <template #default="{ row }">
          <el-tag :type="row.inbound_status">
          {{ getinbound_status(row.inbound_status)}}
        </el-tag>
      </template>
    </el-table-column>
  </el-table>

  <div class="section-header" style="margin-top: 20px;">
    <span class="section-title">出库记录</span>
  </div>

  <el-table :data="outboundRecords" border style="width: 100%; margin-top: 10px;">
    <el-table-column type="index" label="序号" width="60" align="center" />
    <el-table-column prop="outbound_code" label="出库单号" width="150" />
    <el-table-column prop="operate_time" label="出库日期" width="120">
      
      <template #default="{ row }">
        {{ formatDate(row.operate_time) }}
      </template>
    </el-table-column>
    <el-table-column prop="warehouse_id" label="仓库名称" width="120" >
            <template #default="{ row }">
         {{ getStatus(row.warehouse_id) }}
      </template>
      </el-table-column>
    <el-table-column label="商品名称" width="200">
      <template #default="{ row }">
        <div v-for="item in row.detail" :key="item.transfer_id">
            {{ getgoods(item.goods_id) }}
        </div>
      </template>
    </el-table-column>
    <el-table-column label="出库数量" width="100" align="right" >
      <template #default="{ row }">
        <div v-for="item in row.detail" :key="item.transfer_id">
         {{ item.quantity }}
        </div>
      </template>
    </el-table-column>
    <el-table-column  label="出库金额" width="100" align="right" >
      <template #default="{ row }">
        <div v-for="item in row.detail" :key="item.transfer_id">
         {{ item.price }}
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="operator_id" label="经办人" width="100" />
    <el-table-column prop="status" label="状态" width="100" >
      <template #default="{ row }">
         {{ getoutbound_status(row.status) }}
      </template>
      </el-table-column>
    <el-table-column prop="create_time" label="制单时间" width="150">
      <template #default="{ row }">
        {{ formatDate(row.create_time) }}
      </template>
    </el-table-column>
  </el-table>

  <div class="section-header" style="margin-top: 20px;">
    <span class="section-title">入库记录</span>
  </div>

   <el-table :data="inboundRecords" border style="width: 100%; margin-top: 10px;">
    <el-table-column type="index" label="序号" width="60" align="center" />
    <el-table-column prop="inbound_code" label="入库单号" width="150" />
    <el-table-column prop="operate_time" label="出库日期" width="120">
      
      <template #default="{ row }">
        {{ formatDate(row.operate_time) }}
      </template>
    </el-table-column>
    <el-table-column prop="warehouse_id" label="仓库名称" width="120" >
            <template #default="{ row }">
         {{ getStatus(row.warehouse_id) }}
      </template>
      </el-table-column>
    <el-table-column label="商品名称" width="200">
      <template #default="{ row }">
        <div v-for="item in row.inboundrecord" :key="item.transfer_id">
            {{ getgoods(item.goods_id) }}
        </div>
      </template>
    </el-table-column>
    <el-table-column label="入库数量" width="100" align="right" >
      <template #default="{ row }">
        <div v-for="item in row.inboundrecord" :key="item.transfer_id">
         {{ item.quantity }}
        </div>
      </template>
    </el-table-column>
    <el-table-column  label="入库金额" width="100" align="right" >
      <template #default="{ row }">
        <div v-for="item in row.inboundrecord" :key="item.transfer_id">
         {{ item.price }}
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="operator_id" label="经办人" width="100" />
    <el-table-column prop="status" label="状态" width="100" >
      <template #default="{ row }">
         {{ getinbound_status(row.status) }}
      </template>
      </el-table-column>
    <el-table-column prop="create_time" label="制单时间" width="150">
      <template #default="{ row }">
        {{ formatDate(row.create_time) }}
      </template>
    </el-table-column>
  </el-table>

  <div class="dialog-footer">
    <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
  
  </div>
</el-dialog>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { read } from '@/stores/host';
import type { TableInstance } from 'element-plus';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import moment from 'moment';
import { useRouter } from 'vue-router';
const router=useRouter();
const Ikun=()=>{
router.push("/GetWarehouse")
}
// 类型定义
interface Goods {
  id: number;
  name: string;
  code: string;
  specification: string;
  unit: string;
  type: string;
  price: number;
  stock: number;
  goodsType:string;
}

interface Warehouse {
  id: number;
  name: string;
}

interface User {
  id: number;
  name: string;
}

interface MaterialInformation {
  id: number ;
  transfer_id: number;
  goods_id: number | null;
  goods_name: string;
  goods_code: string;
  specification: string;
  unit: string;
  goods_type: string;
  outbound_status: number;
  inbound_status: number ;
  out_stock: string;
  in_stock: string;
  quantity: number | null;
  price: number | null;
  amount: number ;
  remark: string;
  editing: boolean;
  isNew: boolean;
}

interface MainMaterial {
  id: number;
  transfer_no: string;
  transfer_type: string;
  create_time: string;
  out_warehouse_id: number | null;
  in_warehouse_id: number | null;
  operator_id: number | null;
  status: number;
  remark: string;
  detail: MaterialInformation[];
}

interface RuleForm {
  id: number;
  transfer_no: string;
  transfer_type: string;
  create_time: string;
  out_warehouse_id: number | null;
  in_warehouse_id: number | null;
  operator_id: number | null;
  status: number;
  remark: string;
  detail: MaterialInformation[];
}

// 组件逻辑
const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref<MainMaterial[]>([]);
const dialogFormVisible = ref(false);
const detailDialogVisible = ref(false);
const tableData = ref<MainMaterial[]>([]);
const ruleFormRef = ref<FormInstance>();
const currentDetail = ref<MainMaterial>({} as MainMaterial);

const page = reactive({
  totalCount: 0,
  totalPage: 0,
  PageSize: 15,
  PageIndex: 1,
  status: "",
  transfer_no: "",
  outbound_status: "",
  inbound_status: ""
});

const rules = reactive<FormRules<RuleForm>>({
  transfer_type: [
    { required: true, message: '请选择调拨类型', trigger: 'change' }
  ],
  create_time: [
    { required: true, message: '请选择调拨日期', trigger: 'change' }
  ],
  out_warehouse_id: [
    { required: true, message: '请选择调出仓库', trigger: 'change' }
  ],
  in_warehouse_id: [
    { required: true, message: '请选择调入仓库', trigger: 'change' }
  ],
  operator_id: [
    { required: true, message: '请选择经办人', trigger: 'change' }
  ]
});

const ruleForm = reactive<RuleForm>({
  id: 0,
  transfer_no:'',
  transfer_type: "",
  create_time: moment().format('YYYY-MM-DD'),
  out_warehouse_id: null,
  in_warehouse_id: null,
  operator_id: null,
  status: 0,
  remark: "",
  detail: [],
});

const warehouseList = ref<Warehouse[]>([]);
const userList = ref<User[]>([]);
const goodsList = ref<Goods[]>([]);
const outboundRecords = ref<OutboundRecord[]>([]);
const inboundRecords = ref<InboundRecord[]>([]);
// 生成编号
const generateDateBasedNumber = (incrementLength: number = 4): string => {
  const now = new Date();
  const datePart = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
  const storageKey = `dateNumCounter_${datePart}`;
  const lockKey = `dateNumLock_${datePart}`;

  // 尝试获取锁
  let lock = localStorage.getItem(lockKey);
  if (lock) {
    // 如果锁已存在，等待一段时间后重试
    setTimeout(() => {
      generateDateBasedNumber(incrementLength);
    }, 100);
    return ''; // 返回空字符串作为默认值
  }

  localStorage.setItem(lockKey, 'locked');

  // 获取当前计数
  let currentCount = localStorage.getItem(storageKey) || '0';
  const numericCount = parseInt(currentCount, 10) + 1;
  currentCount = numericCount.toString();
  localStorage.setItem(storageKey, currentCount);

  // 释放锁
  localStorage.removeItem(lockKey);

  return datePart + currentCount.padStart(incrementLength, '0');
};

// 创建空子表项
const createEmptySubItem = (isNew: boolean): MaterialInformation => ({
  id: 0,
  transfer_id:0,
  goods_id: null,
  goods_name: "",
  goods_code: "",
  specification: "",
  unit: "",
  goods_type: "",
  outbound_status:0,
  inbound_status: 0,
  out_stock: "",
  in_stock: "",
  quantity: 1,
  price: null,
  amount:0,
  remark: "",
  editing: true,
  isNew
});
// 新增的出库类型定义
interface OutboundRecord {
  id: number;
  outbound_code: string;
  transfer_id: number;
  warehouse_id: number;
  status: number;
  operator_id: number;
  operate_time: Date;
  remark: string;
  detail: {
    id: number;
    transfer_id: number;
     outbound_id: number;
      operator_id: number;
       goods_id: number;
        quantity: number;
    price: number;
     status: number;
     create_time:Date,
    remark: string;
  }[];
}
//入库
interface InboundRecord {
  id: number;
  inbound_code: string;
  create_time: string;
  warehouse_name: string;
  total_quantity: number;
  total_amount: number;
  status: number;
 inboundrecord: {
    id: number;
    transfer_id: number;
     inbound_id: number;
      operator_id: number;
       goods_id: number;
        quantity: number;
    price: number;
     status: number;
     create_time:Date,
    remark: string;
  }[];
}
// 获取调拨数据
const getTransfer = async () => {
  try {
    const res = await read.get("allocateread/api/Transfe/GetTransfe", {
      params: {
        inbound_status: page.inbound_status,
        outbound_status: page.outbound_status,
        transfer_no: page.transfer_no,
        status: page.status,
        PageSize: page.PageSize,
        PageIndex: page.PageIndex
      }
    });
    tableData.value = res.data.data;
    page.totalCount = res.data.totalCount;
    page.totalPage = res.data.totalPage;
  } catch (error) {
    console.error('获取调拨数据失败:', error);
    ElMessage.error('获取数据失败');
  }
};

// 获取基础数据（仓库、用户、商品）
const fetchBaseData = async () => {
  try {
    const [warehouses, users, goods] = await Promise.all([
      read.get('allocateread/api/Transfe/GetWarehouse'),
      read.get('allocateread/api/Transfe/GetUser'),
      read.get('allocateread/api/Transfe/GetGoods')
    ]);

    warehouseList.value = warehouses.data.data || [];
    userList.value = users.data.data || [];
    goodsList.value = goods.data.data || [];
  } catch (error) {
    console.error('获取基础数据失败:', error);
    ElMessage.error('加载基础数据失败');
  }
};

// 表格选择处理
const handleSelectionChange = (val: MainMaterial[]) => {
  multipleSelection.value = val;
};

// 新增配件行
const addHealthRow = () => {
  ruleForm.detail.push(createEmptySubItem(true));
};

// 行操作
const editRow = (row: MaterialInformation) => {
  row.editing = true;
};

const saveRow = (row: MaterialInformation) => {
  row.editing = false;
  row.isNew = false;
};

const cancelEdit = (row: MaterialInformation, index: number) => {
  if (row.isNew) {
    ruleForm.detail.splice(index, 1);
  } else {
    row.editing = false;
  }
};

const deleteRow = (index: number) => {
  ruleForm.detail.splice(index, 1);
};

// 商品选择变化
const handleGoodsChange = (goodsId: number | null, index: number) => {
  if (goodsId === null) {
    // 处理清空选择的情况
    const detailItem = ruleForm.detail[index];
    detailItem.goods_id = null;
    detailItem.goods_name = "";
    detailItem.goods_code = "";
    detailItem.specification = "";
    detailItem.unit = "";
    detailItem.goods_type = "";
    detailItem.price = null;
    return;
  }

  const selectedGoods = goodsList.value.find(g => g.id === goodsId);
  if (selectedGoods) {
    const detailItem = ruleForm.detail[index];
    detailItem.goods_id = selectedGoods.id;
    detailItem.goods_name = selectedGoods.name;
    detailItem.goods_code = selectedGoods.code;
    detailItem.specification = selectedGoods.specification;
    detailItem.unit = selectedGoods.unit;
    detailItem.price = selectedGoods.price;
    detailItem.goods_type = selectedGoods.goodsType;
  }
};

// 计算金额
const calculateAmount = (row: MaterialInformation) => {
  if (row.quantity && row.price) {
    row.amount = row.quantity * row.price;
    return row.amount.toFixed(2);
  }
  row.amount = 0;
  return '0.00';
};


// 新增调拨单
const addMaterial = () => {
  ruleFormRef.value?.resetFields();
  ruleForm.id = 0;
  ruleForm.transfer_no = generateDateBasedNumber();
  ruleForm.transfer_type = "";
  ruleForm.create_time = moment().format('YYYY-MM-DD');
  ruleForm.out_warehouse_id = null;
  ruleForm.in_warehouse_id = null;
  ruleForm.operator_id = null;
  ruleForm.status = 0;
  ruleForm.remark = "";
  ruleForm.detail = [createEmptySubItem(true)];
  dialogFormVisible.value = true;
};

// 编辑调拨单
const updateMaterial = async () => {
  if (multipleSelection.value.length !== 1) {
    ElMessage.warning("请选择一行数据");
    return;
  }

  const selectedRow = multipleSelection.value[0];
  ruleFormRef.value?.resetFields();

  // 主表数据
  ruleForm.id = selectedRow.id;
  ruleForm.transfer_no = selectedRow.transfer_no;
  ruleForm.transfer_type = selectedRow.transfer_type;
  ruleForm.create_time = selectedRow.create_time;
  ruleForm.out_warehouse_id = selectedRow.out_warehouse_id;
  ruleForm.in_warehouse_id = selectedRow.in_warehouse_id;
  ruleForm.operator_id = selectedRow.operator_id;
  ruleForm.status = selectedRow.status;
  ruleForm.remark = selectedRow.remark;

  // 子表数据
  ruleForm.detail = (selectedRow.detail || []).map(item => ({
    ...item,
    editing: false,
    isNew: false
  }));

  dialogFormVisible.value = true;
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  try {
    await formEl.validate();

    // 验证配件信息
    if (ruleForm.detail.length === 0) {
      ElMessage.warning('请至少添加一条配件信息');
      return;
    }

    // 过滤空行
    const validDetail = ruleForm.detail.filter(item => item.goods_id);

    const payload = {
      ...ruleForm,
      detail: validDetail
    };

    const url = ruleForm.id
      ? "allocatewrite/api/Transfer/UpdateTransfer"
      : "allocatewrite/api/Transfer/AddTransfer";

    const method = ruleForm.id ? 'put' : 'post';

    const res = await read[method](url, payload);

    if (res.data.code === 200) {
      ElMessage.success(res.data.message);
      dialogFormVisible.value = false;
      getTransfer();
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    console.error('表单提交错误:', error);
    if (error !== 'cancel') {
      ElMessage.error('提交失败');
    }
  }
};

    const deleteMaterial = async () => {
      if (multipleSelection.value.length === 0) {
        ElMessage.warning('请先选择要删除的数据');
        return;
      }
    
      const row = multipleSelection.value[0];
      const id = Number(row.id);
      
      if (!id) {
        ElMessage.error('选中的数据无效，缺少ID');
        return;
      }
    
      try {
        await ElMessageBox.confirm(
          `确定要删除【${row.transfer_no}】吗？`,
          '删除确认',
          { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        );
    
        const response = await read.post(
          `allocatewrite/api/Transfer/DeleteTransfer?id=${id}`
        );
        
        if (response.data.code === 200) {
          ElMessage.success('删除成功');
          getTransfer();
          multipleTableRef.value?.clearSelection();
        } else {
          ElMessage.error(response.data.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除错误:', error);
          ElMessage.error('删除失败');
        }
      }
    };

// 显示详情
const detailMaterialInformationList = ref<MaterialInformation[]>([]);
// 修改showDetail方法
const showDetail = async (row: MainMaterial) => {
  try {
    currentDetail.value = row;
    detailMaterialInformationList.value = row.detail || [];
    
    // 获取出库记录
    const outboundRes = await read.get(`allocateread/api/Transfe/Getoutbound?Id=${row.id}`);
    outboundRecords.value = outboundRes.data.data || [];
    
    // 获取入库记录
    const inboundRes = await read.get(`allocateread/api/Transfe/Geinbound?Id=${row.id}`);
    inboundRecords.value = inboundRes.data.data || [];
    
    detailDialogVisible.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情数据失败');
  }
};

// 辅助函数
const formatDate = (date: string) => {
  return moment(date).format('YYYY-MM-DD');
};

const getgoods = (goods_id: number) => {
  switch (goods_id) {
    case 1: return '苹果手机';
    case 2: return '电视机';
    case 3: return '咖啡机';
    case 4: return '空调';
    case 5: return '洗衣机';
    default: return '未知状态';
  }
};
const getStatusText = (status: number) => {
  switch (status) {
    case 1: return '待审核';
    case 2: return '驳回';
    case 3: return '正在审核';
    case 4: return '通过';
    case 5: return '已完成';
    default: return '未知状态';
  }
};
const getStatus = (warehouse_id: number) => {
  switch (warehouse_id) {
    case 1: return '第一仓库';
    case 2: return '第二仓库';
    case 3: return '第三仓库';
    case 4: return '第四仓库';
    case 5: return '第五仓库';
      case 6: return '第六仓库';
    case 7: return '第七仓库';
      case 8: return '第八仓库';
    case 9: return '第九仓库';
      case 10: return '第十仓库';

    default: return '未知状态';
  }
};
const getStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'info';
    case 2: return 'danger';
    case 3: return 'success';
     case 4: return 'success';
    default: return 'info';
  }
};

const getoutbound_status = (outbound_status: number) => {
  switch (outbound_status) {
    case 0: return '待出库';
    case 1: return '已出库';
    case 2: return '驳回';
    default: return '未知状态';
  }
};

const getinbound_status = (inbound_status: number) => {
  switch (inbound_status) {
   case 0: return '待入库';
    case 1: return '已入库';
     case 2: return '驳回';
    default: return '未知状态';
  }
};
const getStatusTag = (status: number) => {
  switch (status) {
    case 0: return 'info';
    case 1: return 'success';
        case 2: return 'danger';
    default: return 'info';
  }
};






const getWarehouseName = (id: number | null) => {
  if (!id) return '-';
  const warehouse = warehouseList.value.find(w => w.id === id);
  return warehouse ? warehouse.name : '-';
};

const getUserName = (id: number | null) => {
  if (!id) return '-';
  const user = userList.value.find(u => u.id === id);
  return user ? user.name : '-';
};

// 生命周期
onMounted(() => {
  getTransfer();
  fetchBaseData();
});
</script>

<style scoped>
.transfer-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.action-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.transfer-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding: 15px 20px;
  margin: 0;
}

.transfer-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.transfer-form {
  padding: 20px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.header-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-section {
  margin-top: 30px;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 15px;
  font-weight: bold;
}

.section-actions {
  display: flex;
  gap: 10px;
}

.detail-table {
  margin-top: 0;
}

.table-footer {
  padding: 12px 15px;
  background-color: #f5f7fa;
  border-top: 1px solid #eee;
  text-align: right;
  font-size: 14px;
  color: #666;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  text-align: right;
}

.el-form-item {
  margin-bottom: 18px;
}
</style>